<template>
  <div class="factor-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <h2>因子列表</h2>
          <div>
            <el-button type="primary" @click="$router.push('/factor-management/create')">创建因子</el-button>
            <el-button @click="refreshFactors">刷新</el-button>
          </div>
        </div>
      </template>
      
      <!-- 搜索和筛选区域 -->
      <div class="search-container">
        <el-form :inline="true" class="search-form">
          <el-form-item label="因子名称">
            <el-input v-model="searchName" placeholder="输入因子名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="分类">
            <el-select v-model="searchCategory" placeholder="选择分类" clearable>
              <el-option
                v-for="category in categories"
                :key="category"
                :label="category"
                :value="category">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 因子表格 -->
      <el-table :data="filteredFactors" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column prop="name" label="因子名称" width="150"></el-table-column>
        <el-table-column prop="category" label="分类" width="120"></el-table-column>
        <el-table-column prop="description" label="描述"></el-table-column>
        <el-table-column prop="formula" label="计算公式" width="200"></el-table-column>
        <el-table-column label="操作" fixed="right" width="250">
          <template #default="scope">
            <el-button size="small" @click="viewFactorDetail(scope.row)">查看</el-button>
            <el-button size="small" type="primary" @click="editFactor(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="deleteFactor(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    
    <!-- 因子详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="因子详情"
      width="600px">
      <div v-if="currentFactor">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="因子名称">{{ currentFactor.name }}</el-descriptions-item>
          <el-descriptions-item label="分类">{{ currentFactor.category }}</el-descriptions-item>
          <el-descriptions-item label="描述">{{ currentFactor.description }}</el-descriptions-item>
          <el-descriptions-item label="计算公式">
            <el-tag type="info">{{ currentFactor.formula }}</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="factor-chart" style="height: 300px; margin-top: 20px;">
          <!-- 这里可以放置因子相关的图表，例如因子收益率、IC等 -->
          <div class="chart-placeholder">
            <el-empty description="因子分析图表将在此显示"></el-empty>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'FactorManagement',
  setup() {
    const store = useStore()
    const router = useRouter()
    const searchName = ref('')
    const searchCategory = ref('')
    const detailDialogVisible = ref(false)
    const currentFactor = ref(null)
    
    // 计算属性：获取分类列表
    const categories = computed(() => {
      const categorySet = new Set()
      store.getters.getFactors.forEach(factor => {
        categorySet.add(factor.category)
      })
      return Array.from(categorySet)
    })
    
    // 计算属性：获取过滤后的因子列表
    const filteredFactors = computed(() => {
      return store.getters.getFactors.filter(factor => {
        const nameMatch = !searchName.value || factor.name.includes(searchName.value)
        const categoryMatch = !searchCategory.value || factor.category === searchCategory.value
        return nameMatch && categoryMatch
      })
    })
    
    // 生命周期钩子
    onMounted(() => {
      store.dispatch('loadFactors')
    })
    
    // 方法：搜索因子
    const handleSearch = () => {
      // 搜索逻辑由 filteredFactors 计算属性处理
    }
    
    // 方法：重置搜索
    const resetSearch = () => {
      searchName.value = ''
      searchCategory.value = ''
    }
    
    // 方法：刷新因子列表
    const refreshFactors = () => {
      store.dispatch('loadFactors').then(() => {
        ElMessage.success('因子数据已更新');
      }).catch(error => {
        console.error('刷新因子列表失败:', error);
        ElMessage.warning('数据刷新可能不完整，请查看控制台了解详情');
      });
    }
    
    // 方法：查看因子详情
    const viewFactorDetail = (factor) => {
      currentFactor.value = factor
      detailDialogVisible.value = true
    }
    
    // 方法：编辑因子
    const editFactor = (factor) => {
      // 实际应用中可能需要通过路由参数传递 factor ID
      router.push({
        path: '/factor-management/create',
        query: { id: factor.id, mode: 'edit' }
      })
    }
    
    // 方法：删除因子
    const deleteFactor = (index) => {
      const factor = filteredFactors.value[index];
      ElMessageBox.confirm('确定要删除该因子吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用store中的新action
        store.dispatch('removeFactor', factor.id).then(success => {
          if (success) {
            ElMessage.success('删除成功');
          } else {
            ElMessage.warning('删除操作已执行，但可能未同步到服务器');
          }
        }).catch(() => {
          ElMessage.error('删除失败');
        });
      }).catch(() => {
        // 取消删除
      });
    }
    
    return {
      searchName,
      searchCategory,
      detailDialogVisible,
      currentFactor,
      categories,
      filteredFactors,
      handleSearch,
      resetSearch,
      refreshFactors,
      viewFactorDetail,
      editFactor,
      deleteFactor
    }
  }
}
</script>

<style scoped>
.factor-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-container {
  margin-bottom: 20px;
}

.chart-placeholder {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-color: #f5f7fa;
}
</style> 